package main

import (
	"fmt"
	"net"
	"time"
)

type cmdServer struct {
	id       string
	addr     *net.TCPAddr
	listener *net.TCPListener
	terminal bool
	devServ  *deviceServer
}

func (s *cmdServer) start(port string) {
	var err error
	s.terminal = false
	s.addr, err = net.ResolveTCPAddr("tcp", port)
	checkError(err)
	listener, err := net.ListenTCP("tcp", s.addr)
	checkError(err)
	fmt.Println(s.id + ":listener  ")
	s.listener = listener
	go s.run(listener)
}
func (s *cmdServer) run(listener *net.TCPListener) {
	if listener == nil {
		return
	}
	i := 0
	for {
		conn, err := listener.Accept()
		fmt.Println("conn  ")
		if s.terminal {
			return
		}
		if err != nil {
			continue
		}
		i++
		thisTime := mytime()
		fmt.Println(s.id+":new request", i, " from ", conn.RemoteAddr(), "  return time", thisTime)
		go func() {
			var mybuff [512]byte
			conn.SetReadDeadline(time.Now().Add(10000 * time.Millisecond))
			n, err := conn.Read(mybuff[0:])
			if err != nil {
				fmt.Println("Must be read data,but nothing!!!")
			}
			conn.Close()
			fmt.Println("read byte:", n)
			fmt.Println(mybuff[0:n])
			s.devServ.transmit(mybuff[0:n])
		}()

	}
}
func (s *cmdServer) stop() {
	s.terminal = true
	if s.listener != nil {
		s.listener.Close()
	}
}
